﻿using System.Collections.Generic;
using UnityEngine;

namespace GameDesigner
{
    public class AnimatorStateMachineView : StateMachineView
    {
        public Animator animator;

        public override void Init(params object[] args)
        {
            controller.Init(this, (layer) => new AnimatorStateMachine(animator, layer), args);
        }

#if UNITY_EDITOR
        public override void GetClipNames(Transform root, List<string> clipNames)
        {
            if (animator == null)
                animator = root.GetComponentInChildren<Animator>();
            GetClipNames(animator, clipNames);
            if (animClipReference is IAnimationClipReference animationClipReference)
            {
                clipNames.Clear();
                clipNames.AddRange(animationClipReference.ClipNames);
            }
        }

        public override float GetAnimClipLength(StateAction action)
        {
            return GetAnimClipLength(animator, action);
        }

        public static void GetClipNames(Animator animator, List<string> clipNames)
        {
            if (animator == null)
                return;
            if (animator.runtimeAnimatorController is UnityEditor.Animations.AnimatorController controller)
            {
                clipNames.Clear();
                foreach (var layer in controller.layers)
                {
                    var states = layer.stateMachine.states;
                    foreach (var state in states)
                        clipNames.Add(state.state.name);
                }
            }
        }

        public static float GetAnimClipLength(Animator animator, StateAction action)
        {
            if (animator.runtimeAnimatorController is UnityEditor.Animations.AnimatorController controller)
            {
                if (controller.layers.Length <= 0) //打AB包后选择这里是0
                    return 0f;
                float GetAnimClipLengthIn(int layerIndex, string clipName)
                {
                    var layer = controller.layers[layerIndex];
                    var states = layer.stateMachine.states;
                    foreach (var state in states)
                    {
                        if (state.state.name != clipName)
                            continue;
                        if (state.state.motion is AnimationClip clip)
                            return clip.length;
                        break;
                    }
                    return 0f;
                }
                if (action.Layer.LayerIndex != -1)
                    return GetAnimClipLengthIn(action.Layer.LayerIndex, action.clipName);
                for (int i = 0; i < controller.layers.Length; i++)
                {
                    var length = GetAnimClipLengthIn(i, action.clipName);
                    if (length > 0f) return length;
                }
            }
            return 0f;
        }
#endif
    }
}